package com.simin.base.apputils

import android.Manifest
import android.app.Activity
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.widget.PopupWindow
import androidx.core.content.ContextCompat
import androidx.fragment.app.FragmentActivity
import com.simin.base.appdialog.PopupWindowManager
import com.tbruyelle.rxpermissions2.Permission
import com.tbruyelle.rxpermissions2.RxPermissions
import io.reactivex.functions.Consumer

/**
 * Created by wsm on 2024/9/13.
 * <p>权限申请工具类
 *
 */
object PermissionUtils {
    private var popupWindow: PopupWindow? = null;

    /**
     * 检测权限是否授权
     */
    fun checkPermission(
        activity: Activity,
        title: String,
        content: String,
        permissions: Array<String>
    ) {
        permissions.forEach { permission ->
            when {
                ContextCompat.checkSelfPermission(
                    activity,
                    permission
                ) != PackageManager.PERMISSION_GRANTED -> {
                    //一个没授权都返回false
                    if (popupWindow == null) {
                        popupWindow =
                            PopupWindowManager.showPermissionApply(activity, title, content)
                    }
                }
            }
        }
    }

    //申请拍摄存储权限
    fun checkPermissionCameraStorage(activity: FragmentActivity, callback: PermissionsCallback?) {
        var rxPermissions = RxPermissions(activity)
        val permission = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            arrayOf(
                Manifest.permission.READ_MEDIA_IMAGES,
                Manifest.permission.READ_MEDIA_VIDEO
            )
        } else {
            arrayOf(
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE
            )
        }
        // //查询是否授权
        checkPermission(
            activity,
            "\uD83D\uDDBC\uFE0F 图片上传相关权限",
            getPermissionContent(3),
            permission
        )
        rxPermissions.request(
            *permission
        ).subscribe { granted: Boolean ->
            if (granted) {
                //所有的权限都授予
                callback?.onGranted()
                dismissPop()
            } else {
                //至少一个权限未授予且勾选了不再提示
//                MatisseUtils.showDialog(activity)
                dismissPop()
            }
        }
    }

    //申请摄像头权限
    fun checkPermissionCamera(activity: FragmentActivity, callback: PermissionsGrantedCallback?) {
        var rxPermissions = RxPermissions(activity)
        val permission = arrayOf(
            Manifest.permission.CAMERA,
            Manifest.permission.RECORD_AUDIO
        )
        // //查询是否授权
        checkPermission(
            activity,
            "\uD83D\uDCF7 相机和麦克风权限",
            getPermissionContent(0),
            permission
        )
        rxPermissions.request(
            *permission
        ).subscribe { granted: Boolean ->
            if (granted) {
                //所有的权限都授予
                callback?.onGranted()
                dismissPop()
            } else {
                //至少一个权限未授予且勾选了不再提示
                callback?.onTips()
                dismissPop()
            }
        }
    }

    //申请通知权限
    fun checkPermissionNotification(
        activity: FragmentActivity,
        callback: PermissionsGrantedCallback?
    ) {
        var rxPermissions = RxPermissions(activity)
        rxPermissions.request(
            Manifest.permission.POST_NOTIFICATIONS
        ).subscribe { granted: Boolean ->
            if (granted) {
                //所有的权限都授予
                callback?.onGranted()
                dismissPop()
            } else {
                //至少一个权限未授予且勾选了不再提示
                callback?.onTips()
                dismissPop()
            }
        }
    }

    //申请存储权限
    fun checkPermissionStorage(fragment: FragmentActivity, callback: PermissionsCallback?) {
        var rxPermissions = RxPermissions(fragment)
        val permission = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            arrayOf(
                Manifest.permission.READ_MEDIA_IMAGES
            )
        } else {
            arrayOf(
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.READ_EXTERNAL_STORAGE
            )
        }
        // //查询是否授权
        checkPermission(
            fragment,
            "\uD83D\uDCBE 报告存储权限",
            getPermissionContent(1),
            permission
        )
        rxPermissions.request(
            *permission
        ).subscribe { granted: Boolean ->
            if (granted) {
                //所有的权限都授予
                callback?.onGranted()
                dismissPop()
            } else {
                //至少一个权限未授予且勾选了不再提示
//                MatisseUtils.showDialog(fragment)
                dismissPop()

            }
        }
    }

    //拨打电话
    fun checkPermissionPhone(mActivity: FragmentActivity, phone: String) {
        val permission = arrayOf(
            Manifest.permission.CALL_PHONE
        )
        // //查询是否授权
        checkPermission(mActivity, "拨打电话权限", getPermissionContent(2), permission)
        var rxPermissions = RxPermissions(mActivity)
        rxPermissions.request(
            *permission
        )
            .subscribe { granted: Boolean ->
                if (granted) {
                    //所有的权限都授予
                    mActivity.startActivity(Intent(Intent.ACTION_DIAL, Uri.parse("tel:$phone")))
                    dismissPop()
                } else {
                    //至少一个权限未授予且勾选了不再提示
//                    MatisseUtils.showDialog(mActivity)
                    dismissPop()
                }
            }
    }


    //权限授权回调
    interface PermissionsCallback {
        fun onGranted()
    }

    //权限授权回调
    interface PermissionsGrantedCallback : PermissionsCallback {
        fun onTips();
    }

    /**
     * type 权限类型 0 相机 1存储 2拨号 3相机存储
     */
    fun getPermissionContent(type: Int): String {
        if (type == 0) {
            //相机和麦克风
            return "用途说明：视频咨询期间需启用摄像头与麦克风，确保您与用户沟通流畅。咨询结束后自动关闭摄像头和麦克风权限，后台无任何残留访问。"
        } else if (type == 1) {
            //存储
            return "用途说明：当您选择「保存至相册」时，我们仅申请单次写入权限。您可随时在系统相册管理中删除文件，我们不会保留副本。"
        } else if (type == 2) {
            //拨号
            return "用途说明：为给您提供更便捷的服务，我们需要申请「拨打电话」权限，我们承诺：仅在您主动点击拨号按钮时触发，绝不收集通话内容或通讯录信息，可随时在手机设置中关闭此权限"
        } else {
            //相机和存储
            return "涉及场景：\n" +
                    "头像设置、图片上传提交等\n" +
                    "保护承诺：\n" +
                    "我们仅访问您手动选择的照片/文件，绝不扫描整个相册。上传后立即释放权限，所有数据均加密存储。"
        }
    }

    /**
     * 关闭授权提示
     */
    fun dismissPop() {
        if (popupWindow != null && popupWindow!!.isShowing) {
            popupWindow?.dismiss()
            popupWindow = null;
        }
    }

}